<script setup lang="ts">
import { ref,onMounted, watch } from 'vue';
import { useStore } from "vuex";
import axios from "axios";
import {ElMessage} from "element-plus";

const store = useStore();
const showAIfloatWindow = ref(false);
const userInput = ref('');
const chatHistory = ref([]);

const initializeChat= async () => {
  try {
    const res = await axios.post('/api/chat/start', {
      userId: store.getters.userId,
    initialMessage: "你好，我是一个智能助手，请问有什么可以帮助你的？",
    });
    chatHistory.value = [
      {
        sender: 'ai',
        text: res.data.response
      }];
  } catch (error){
    console.log(error);
    ElMessage.error("初始化失败");
    chatHistory.value = [{
      sender: 'ai',
      text: "抱歉，AI服务暂时无法访问，请稍后再试。"
    }];
  }
};

const sendMessgae = async () => {
  if (!userInput.value) return

  chatHistory.value.push({
    sender: 'user',
    text: userInput.value
  });

  userInput.value = '';
  try {
    const res = await axios.post('/api/ai/chat/message', {
      sessionId: store.getters.sessionId,
      message: userInput.value
    });

    chatHistory.value.push({
      sender: 'ai',
      text: res.data.response
    });
  }catch ( error){
    ElMessage.error("发送失败");
    console.log( error)
    chatHistory.value.push({
      sender: 'ai',
      text: "抱歉，AI服务暂时无法访问，请稍后再试。"
    })
  }
};

const closewindow = () => {
  showAIfloatWindow.value = false;
  chatHistory.value = [];
};

const openWindow = () => {
  showAIfloatWindow.value = true;
  initializeChat();
};

const handleShortcut = (event) => {
 if (event.key === 'F1' && event.ctrlkey){
   event.preventDefault();
   openWindow();
 }
};

onMounted(() => {
  document.addEventListener('keydown', handleShortcut);
  const activeSession = store.getters.activeChatSession;
  if (activeSession){
    showAIfloatWindow.value = true;
    chatHistory.value = activeSession.message;
  }
})

watch(() => store.getters.activeChatSession, (newSession) => {
  if (newSession){
    chatHistory.value = newSession.message;
  }
})

defineExpose({
  openWindow
})
</script>

<template>
 <div v-if="showAIfloatWindow" class="ai-float-window">
   <div class="header">
     <span>AI 助手</span>
     <button @click="closWindow" class="close-btn">x</button>
   </div>
   <div class="chat-container">
     <div v-for="(message, index) in chatHistory" :key="index" :class="['message',message.sender]">
       {{ message.text}}
     </div>
   </div>
   <div class="input-continer">
     <input v-model="userInput" @keyup.enter="sendMessgae" placeholder="请输入你的问题" class="input-box"/>
     <button @click="sendMessgae" class="send-btn">发送</button>
   </div>
 </div>
</template>

<style scoped>
.ai-float-window{
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 400px;
  height: 600px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 0 15px rgba(0,0,0,0.2);
  display: flex;
  flex-direction: column;
  z-index: 1000;
  overflow: hidden;
}
.header{
  padding: 12px 16px;
  background: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  font-weight: bold;
}
.close-btn{
  background: none;
  border: none;
  font-size: 1.2em;
  cursor: pointer;
  color: #666;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition:  all 0.2s;
}
.close-btn:hover{
  background: #e0e0e0;
  color: #333;
}
.chat-container{
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.message {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 18px;
  word-break: break-word;
}
.message.user{
  margin-left: auto;
  background: #e3f2fd;
  border-bottom-right-radius: 5px;
}
.message.ai{
  margin-right: auto;
  background: #f0f0f0;
  border-bottom-left-radius: 5px;
}
.input-continer{
  padding: 10px 15px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 8px;
}
.input-box{
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
}
.input-box:focus{
  border-color: #409eff;
}
.send-btn{
  background: #409eff;
  color: white;
  border: none;
  padding: 0 20px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.2s;
}
.send-btn:hover{
  background: #66b1ff;
}
</style>